from django.contrib import admin
from django.forms import TextInput, Widget
from .models import WechatUserInfo, WechatPayment, AppResource
from constance.admin import ConstanceAdmin, Config
from constance import config

# 注册微信用户信息模型
@admin.register(WechatUserInfo)
class WechatUserInfoAdmin(admin.ModelAdmin):
    list_display = ('openid', 'nickname', 'gender', 'city', 'province', 'country', 'created_at')
    search_fields = ('openid', 'nickname')
    list_filter = ('gender', 'city', 'province', 'country')

# 注册微信支付记录模型
@admin.register(WechatPayment)
class WechatPaymentAdmin(admin.ModelAdmin):
    list_display = ('user', 'transaction_id', 'out_trade_no', 'total_fee', 'status', 'created_at', 'ip_address')
    search_fields = ('transaction_id', 'out_trade_no')
    list_filter = ('status', 'created_at')

# 自定义 Constance 配置管理界面
class CustomConfigAdmin(ConstanceAdmin):
    # 定义不可编辑的配置项
    readonly_config_fields = {
        'WECHAT_APP_ID',
        'WECHAT_APP_SECRET',
        'WECHAT_MCH_ID',
        'WECHAT_MCH_KEY',
        'WECHAT_NOTIFY_URL',
    }
    
    def get_config_value(self, name, options, form, initial):
        config = super().get_config_value(name, options, form, initial)
        if isinstance(config, dict) and 'value' in config:
            # 移除默认值显示
            config.pop('default', None)
            # 如果是只读配置项，禁用输入
            if name in self.readonly_config_fields:
                if config.get('field'):
                    config['field'].widget.attrs['readonly'] = True
                    config['field'].widget.attrs['class'] = 'readonly-field'
            # 调整输入框宽度
            if config.get('field'):
                config['field'].widget.attrs['style'] = 'width: 50%;'
        return config

    class Media:
        css = {
            'all': ('admin/css/custom_constance.css',)
        }

    def has_change_permission(self, request, obj=None):
        if obj and obj.key in self.readonly_config_fields:
            return False
        return super().has_change_permission(request, obj)

# 重新注册 Constance Config
admin.site.unregister([Config])
admin.site.register([Config], CustomConfigAdmin)
# 微信小程序资源库
@admin.register(AppResource)
class AppResourceAdmin(admin.ModelAdmin):
    list_display = ('name', 'page', 'type', 'key', 'value', 'is_active', 'updated_at')
    list_filter = ('page', 'type', 'is_active')
    search_fields = ('name', 'key', 'value')
    ordering = ('page', 'type', 'name')
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'page', 'type', 'key')
        }),
        ('资源内容', {
            'fields': ('value', 'description', 'is_active')
        })
    )

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑时
            return ('key', 'page', 'type')  # 创建后这些字段不可修改
        return ()

    class Media:
        css = {
            'all': ('admin/css/custom_resource.css',)
        }
